import React, { useEffect, useState } from "react";
//import LoginTextField from "TextField";
import './styles/LoginTextField.css'
import { Button, IconButton, Stack } from "@mui/material";
import axios from "axios";
import { InputAdornment } from "@mui/material";
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import Alert from '@mui/material/Alert';
import CheckIcon from '@mui/icons-material/Check';
import { useNavigate, useLocation, Navigate } from "react-router-dom";
import { jwtDecode } from "jwt-decode";


const AutoDismissAlert = ({ severity, message, onClose, timeout }) => {
    const [open, setOpen] = useState(true);

    useEffect(() => {
        const timer = setTimeout(() => {
            setOpen(false);
            onClose(); // Вызовите функцию onClose, если она передана
        }, timeout);

        return () => {
            clearTimeout(timer);
        };
    }, [onClose, timeout]);

    if (!open) return null;

    return (
        <Stack sx={{ width: '100%' }} spacing={2}>
            <Alert severity={severity} onClose={() => { setOpen(false); onClose(); }}>
                {message}
            </Alert>
        </Stack>
    );
};



function LoginForm() {
    let navigate = useNavigate();
    let location = useLocation();
    const [show, setShow] = useState(true)
    let from = location.state?.from?.pathname || "/home";
    const [password, setPassword] = useState("")
    const [email, setEmail] = useState("")

    const [showPassword, setShowPassword] = React.useState(false);
    const [isValidEmail, setIsValidEmail] = useState(true);
    const [isValidPassword, setIsValidPassword] = useState(true);
    const [error, setError] = useState(null);


    const emailValidator = (input) => {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input)
    }

    const passwordValidator = (input) => {
        return input.trim().split(' ').length >= 2
    }

    const handleInputChangePassword = (e) => {
        const input = e.target.value;
        setPassword(input);
        setIsValidPassword(passwordValidator(input));
    };

    const handleInputChangeEmail = (e) => {
        const input = e.target.value;
        setEmail(input);
        setIsValidEmail(emailValidator(input));
    };

    const handleClickShowPassword = () => setShowPassword((show) => !show);

    function login() {
        const body = {
            "email": "",
            "password": ""
        }
        body["email"] = email;
        body["password"] = password;
        const headers = { 
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
          }
        axios.post('http://localhost:8000/api/login', body, {headers: headers})
            .then((response) => {
                localStorage.setItem('accessToken', response.data.accessToken)
                const decoded = jwtDecode(localStorage.getItem("accessToken"))
                navigate('/chat')
            })
            .catch((error) => {
                // if (error.response.status === 401) {
                //     setError('Ошибка входа: Неверные учетные данные');
                // }
            })
    }

    const handleClose = () => {
        setError(null);
    };


    return (
        <div style={{ display: "flex", flexDirection: 'column', justifyContent: 'center', alignItems: 'center', minHeight: '100%', width: 'auto', paddingTop: '100px' }}>
            <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '50%', width: '40%', borderRadius: '7px', padding: '20px', background: 'transparent' }}>
                {error && (
                    <AutoDismissAlert severity="error" message={error} onClose={handleClose} timeout={5000} />

                )}
                <p style={{ color: "rgb(0, 184, 9)", fontSize: 30, fontWeight: '900' }}>Авторизация</p>
                <div className='input-container'>
                    <label>Почта</label>
                    <input
                        type={"email"}
                        value={email}
                        onChange={handleInputChangeEmail}
                        style={{ borderColor: 'rgb(0, 184, 9)' }}
                    />
                    {!isValidEmail && <p className="error-message">Введите корректный email</p>}
                </div>
                <div className='input-container'>
                    <label>Пароль</label>
                    <input
                        value={password}
                        onChange={handleInputChangePassword}
                        style={{ borderColor: 'rgb(0, 184, 9)' }}
                        type={showPassword ? 'text' : 'password'}

                    >
                    </input>
                    <InputAdornment sx={{ zIndex: 1, position: 'absolute', right: '00px', top: '70px' }}>
                        <IconButton
                            onClick={handleClickShowPassword}
                            edge="end"
                        >
                            {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                    </InputAdornment>
                    {/* helperText={this.state.password1 !== this.state.password2 ? "Пароли не совпадают" : !this.state.password1Entered && this.state.password1.length !== 0 ? <> Пароль должен содержать: <br /> - Заглавную букву <br /> - Строчную букву <br /> - Один специальный символ (- # ! $ @ % ^ & * _ + |  = ? , . /) \<br /> - Минимум 8 знаков </> : "Введите пароль"} */}

                    {/* {!isValidPassword && <p className="error-message">ФИО должно содержать хотя бы два слова</p>} */}
                </div>
                <Button onClick={login} sx={{ width: '50%', color: 'white', borderRadius: '15px', backgroundColor: 'rgb(0, 184, 9)', '&:focus': { backgroundColor: 'rgb(0, 184, 9)' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }} variant={'contained'}>
                    Войти
                </Button>
            </div>
        </div>
    )
}
export default LoginForm;